React에서 만든 별점 등록기

✒️ 2025-05-16 12:34 내용 수정


  1. 마우스를 올려 놓거나 마우스가 나갈 때 별점 채워짐 처리
// 마우스가 들어오고 나갈 때 처리
import { useState } from "react";
import { StarFill } from "react-bootstrap-icons";

function StarSelect() {
        const totalStar = 5;
        const [hoverIndex, setHoverIndex] = useState(-1);
        const [score, setScore] = useState(0);

        const defaultStyle = { color: '#bebdbd' } // 짙은 노란색
        const hoverStyle = { color : '#FFC100' } // 회색
    
        function handleMouseEnter(index) { // 마우스 올려 놓을 때 색 바뀌기 처리
             setHoverIndex(index);
        }
        
        function handleMouseLeave() { // 마우스 벗어날 때 색 바뀌기 처리
            setHoverIndex(-1);
        }

        const star = Array.from({length:totalStar}, (_, index) => ( // element는 사용 안하므로 "_" 표시
            <StarFill 
            key={index} 
            {/* 현재의 인덱스가 hover 인덱스보다 작으면 스타일을 다르게 적용한다. */}
            style={index <= hoverIndex ? hoverStyle : defaultStyle} 
            onMouseEnter={()=>{handleMouseEnter(index)}}
            onMouseLeave={handleMouseLeave}
			}
            />
        ));
    
        return(
            <div>
                {star}
            </div>
        )
}

export default StarSelect;
  1. 마우스로 별을 클릭했을 때 별점 채워짐 처리
// 마우스 클릭 시 처리
import { useState } from "react";
import { StarFill } from "react-bootstrap-icons";

function StarSelect() {
        const totalStar = 5;
        const [hoverIndex, setHoverIndex] = useState(-1);
        const [score, setScore] = useState(0);

        const defaultStyle = { color: '#bebdbd' } // 짙은 노란색
        const hoverStyle = { color : '#FFC100' } // 회색
    
        function handleClick(index) { // 클릭 처리
            setScore(index + 1); // 클릭한 위치의 인덱스를 저장한다.
            setHoverIndex(index); // hover 인덱스를 저장하여 스타일을 변경에 사용한다.
        }

        const star = Array.from({length:totalStar}, (_, index) => ( // element는 사용 안하므로 "_" 표시
            <StarFill 
            key={index} 
            {/* 현재의 인덱스가 hover 인덱스보다 작으면 스타일을 다르게 적용한다. */}
            style={index <= hoverIndex ? hoverStyle : defaultStyle} 
            onClick={()=>{handleClick(index)}}
            />
        ));
    
        return(
            <div>
                {star}
            </div>
        )
}

export default StarSelect;

star gage 1.png
star gage 2.png

star gage 3.png
star gage 4.png